package service

import (
	"github.com/gin-gonic/gin"
	"github.com/asaskevich/govalidator"
	"github.com/gorilla/websocket"
	"go_part/models"
	"strconv"
	"fmt"
	"math/rand"
	"go_part/utils"
	"net/http"
	"time"
  )

// GetUserList
// @Tags         获得用户列表
// @Success      200  {string}  json{"code","message"}
// @Router       /user/getUserList [get]
func GetUserList(c *gin.Context) {

	data := make([]*models.UserBasic,10)
	data = models.GetUserList()

	c.JSON(200, gin.H{
		"message": data,
	  })
}

// CreateUser
// @Tags         创建新用户
// @Param name query string false "用户名"
// @Param password query string false "密码"
// @Param repassword query string false "确认密码"
// @Param CompanyID query string false "公司ID"
// @Param CompanyPassword query string false "邀请码"
// @Success      200  {string}  json{"code","message"}
// @Router       /user/CreateUser [get]
func CreateUser(c *gin.Context) {

	user := models.UserBasic{}
	user.Name = c.Query("name")
	passWord := c.Query("password")
	repassWord := c.Query("repassword")
	user.CompanyID = c.Query("CompanyID")
	CompanyPassword := c.Query("CompanyPassword")

	salt := fmt.Sprintf("%06d",rand.Int31())

	data := models.FindUserByName(user.Name)
	if data.Name != "" {
		c.JSON(-1 ,gin.H{
			"message": "用户名已存在",
		  })
		return
	}

	data1 := models.FindCompanyByID(user.CompanyID)
	if data1.Name == "" {
		c.JSON(-1 ,gin.H{
			"message": "公司名不存在",
		  })
		return
	}

	if data1.PassWord != CompanyPassword {
		c.JSON(-1 ,gin.H{
			"message": "邀请码不正确",
		  })
		return
	}

	if passWord != repassWord {
		c.JSON(-1 ,gin.H{
			"message": "两次密码不一致",
		  })
		return
	}
	//user.PassWord = passWord
	user.PassWord = utils.MakePassword(passWord,salt)
	user.Salt = salt
	models.CreateUser(user)
	c.JSON(200 ,gin.H{
		"message": "新增用户成功！",
	  })
}

// DeleteUser
// @Tags         删除用户
// @Param id query string false "id"
// @Success      200  {string}  json{"code","message"}
// @Router       /user/DeleteUser [get]
func DeleteUser(c *gin.Context) {

	user := models.UserBasic{}
	id, _ := strconv.Atoi(c.Query("id"))
	user.ID = uint(id)

	models.DeleteUser(user)
	c.JSON(200 ,gin.H{
		"code": 0,
		"message": "删除用户成功！",
	  })
}

// UpdateUser
// @Tags         更新用户
// @Param id formData string false "id"
// @Param name formData string false "name"
// @Param password formData string false "password"
// @Param phone formData string false "phone"
// @Param email formData string false "email"
// @Success      200  {string}  json{"code","message"}
// @Router       /user/UpdateUser [post]
func UpdateUser(c *gin.Context) {

	user := models.UserBasic{}
	id, _ := strconv.Atoi(c.PostForm("id"))
	user.ID = uint(id) 
	user.Name = c.PostForm("name")
	user.PassWord = c.PostForm("password")
	user.Phone = c.PostForm("phone")
	user.Email = c.PostForm("email")

	govalidator.ValidateStruct(user)

	models.UpdateUser(user)
	c.JSON(200 ,gin.H{
		"code": 0,
		"message": "更新用户成功！",
	  })
}

// FindUserByNameAndPwd
// @Tags         登录
// @Param name query string false "用户名"
// @Param password query string false "密码"
// @Success      200  {string}  json{"code","message"}
// @Router       /user/FindUserByNameAndPwd [post]
func FindUserByNameAndPwd(c *gin.Context) {

	data := models.UserBasic{}

	name := c.Query("name")
	password := c.Query("password")
	user := models.FindUserByName(name)
	if user.Name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"message": "用户不存在",
		  })
		  return
	}

	flag := utils.VaildPassword(password,user.Salt,user.PassWord)
	if !flag {
		c.JSON(200, gin.H{
			"code": 500,
			"message": "密码不正确",
		  })
		  return
	}

	pwd := utils.MakePassword(password, user.Salt)
	data = models.FindUserByNameAndPwd(name,pwd)

	c.JSON(200, gin.H{
		"code": 0,
		"message": data,
	  })
}

var upGrade = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func SendMsg(c *gin.Context){
	ws,err := upGrade.Upgrade(c.Writer,c.Request,nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func(ws *websocket.Conn){
		err = ws.Close()
		if err !=nil {
			fmt.Println(err)
		}
	}(ws)
	MsgHandler(ws, c)
}

func MsgHandler(ws * websocket.Conn,c *gin.Context){
	for {
		msg,err := utils.Subscribe(c, utils.PublicKey)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println("发送消息： ",msg)
		tm := time.Now().Format("2025-01-02")
		m := fmt.Sprintf("[ws][%s]:%s",tm,msg)
		err = ws.WriteMessage(1, []byte(m))
		if err != nil {
			fmt.Println(err)
		}
	}

}

func SendUserMsg(c *gin.Context){
	models.Chat(c.Writer, c.Request)
}

func SearchFrient(c *gin.Context){
	id,_ := strconv.Atoi(c.Query("userId"))
	users := models.SearchFrient(uint(id))

	// c.JSON(200, gin.H{
	// 	"code": 0,
	// 	"message": user,
	//   })
	utils.RespOKList(c.Writer,users,len(users))
}

func AddFriend(c *gin.Context){
	userId,_ := strconv.Atoi(c.Query("userId"))
	targetId,_ := strconv.Atoi(c.Query("targetId"))
	code,msg := models.AddFriend(uint(userId),uint(targetId))

	// c.JSON(200, gin.H{
	// 	"code": 0,
	// 	"message": user,
	//   })
	if code == 0 {
		utils.RespOK(c.Writer,msg)
	}else {
		utils.RespFail(c.Writer,msg)
	}
	
}

func CreateCommunity(c *gin.Context) {
	ownerId,_ := strconv.Atoi(c.Query("ownerId"))
	Name := c.Query("Name")
	community := models.Community{}
	community.OwnerId = uint(ownerId)
	community.Name = Name
	code,msg := models.CreateCommunity(community)

	if code == 0 {
		utils.RespOK(c.Writer,msg)
	}else {
		utils.RespFail(c.Writer,msg)
	}
}

func LoadCommunity(c *gin.Context) {
	ownerId,_ := strconv.Atoi(c.Query("ownerId"))
	//Name := c.Query("Name")
	data,msg := models.LoadCommunity(uint(ownerId))

	if len(data) != 0 {
		utils.RespOKList(c.Writer,data,msg)
	}else {
		utils.RespFail(c.Writer,msg)
	}
}

func JoinGroup(c *gin.Context) {
	userId,_ := strconv.Atoi(c.Query("userId"))
	comId,_ := strconv.Atoi(c.Query("comId"))
	data,msg := models.JoinGroup(uint(userId),uint(comId))
	if data != 0 {
		utils.RespOKList(c.Writer,data,msg)
	}else {
		utils.RespFail(c.Writer,msg)
	}
}